import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;

public class Solution4 {
    public static void main(String[] args) {
        int[][] grid = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}};
        System.out.println(maxDistance(grid));
    }
    public static int maxDistance(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};
        int[][] dist = new int[m][n];
        Queue<int[]> q = new LinkedList<>();
        for(int i = 0; i < m; i++) {
            Arrays.fill(dist[i], -1);
        }

        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == 1) {
                    dist[i][j] = 0;
                    q.add(new int[]{i, j});
                }
            }
        }

        int ret = -1;
        while(!q.isEmpty()) {
            int[] t = q.poll();
            int a = t[0];
            int b = t[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && dist[x][y] == -1) {
                    dist[x][y] = dist[a][b] + 1;
                    q.add(new int[]{x, y});
                    ret = Math.max(ret, dist[x][y]);
                }
            }
        }
        return ret;
    }
}
